<template>
    <div class="login">
        <!-- <h1>成功登录</h1>
        <router-view /> -->

        <!-- 顶部菜单栏 -->
        <!-- 添加该样式沾满全屏style="position: absolute;left: 0;top: 0;bottom: 0;right: 0;" -->
        <el-container style="position: absolute;left: 0;top: 0;bottom: 0;right: 0;overflow: hidden;">
            <!-- class="d-flex"是bootstrap的样式直接引用 
            bootstrap可以通过d-flex实现一行布局 -->
            <el-header class="d-flex align-items-center" style="background-color: #545c64;">
                <a class="h6 text-white mb-0 mr-auto" href="">{{ $conf.logo }}</a>
                <el-menu :default-active="navBar.active" mode="horizontal" @select="handleSelect"
                    background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
                    <!-- <el-menu-item :index="index.toString()" v-for="(item,index) in navBar.list" :key="index">{{ item.name }}</el-menu-item> -->
                    <!-- 过滤器写法 -->
                    <el-menu-item :index="index | numToString" v-for="(item, index) in navBar.list" :key="index">{{
                        item.name }}</el-menu-item>
                    <el-submenu index="100">
                        <template slot="title">
                            <el-avatar size="small"
                                :src="user.avatar ? user.avatar : require('@/assets/pic.jpg')"></el-avatar>
                            {{ user.username }}
                        </template>
                        <el-menu-item index="100-1">修改</el-menu-item>
                        <el-menu-item index="100-2">退出</el-menu-item>
                    </el-submenu>
                </el-menu>
            </el-header>

            <!-- 侧边导航栏，其对应的导航应当与顶部导航栏相对应 -->
            <!-- 设置侧边栏可以滚动且完全显示 -->
            <el-container style="height: 100%;">
                <!-- 侧边布局 -->
                <el-aside width="200px">
                    <!-- <li v-for="i in 100" :key="i">{{ i }}</li> -->
                    <!-- 动态绑定默认选中的计算属性 -->
                    <el-menu :default-active="String(sildeMenusActive)" @select="sildeSelect" style="height: 100%;">
                        <el-menu-item :index="index | numToString" v-for="(item, index) in slideMenus" :key="index">
                            <i :class="item.icon"></i>
                            <span slot="title">{{ item.name }}</span>
                        </el-menu-item>
                        <!-- <el-menu-item index="2">
                            <i class="el-icon-document"></i>
                            <span slot="title">导航三</span>
                        </el-menu-item>
                        <el-menu-item index="3">
                            <i class="el-icon-setting"></i>
                            <span slot="title">导航四</span>
                        </el-menu-item> -->
                    </el-menu>
                </el-aside>


                <!-- 主体布局 -->
                <el-main class="bg-light" style="padding-bottom: 20px; position: relative;" v-loading='loading'>
                    <!-- <li v-for="i in 100" :key="i">{{ i }}</li> -->
                    <!-- 面包屑导航 -->
                    <div class="border-bottom bg-white" style="padding: 20px; margin: -20px; margin-bottom: 10px;"
                        v-if="bran.length > 0">
                        <el-breadcrumb separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item v-for="item in bran" :key="item.id" :to="{ path: item.path }">
                                {{ item.title }}</el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                    <!-- 主内容的位置 -->
                    <router-view />
                    <el-backtop target=".el-main" :bottom="100">
                        <div style="
                                    height: 100%;
                                    width: 100%;
                                    background-color: #f2f5f6;
                                    box-shadow: 0 0 6px rgba(0,0,0, .12);
                                    text-align: center;
                                    line-height: 40px;
                                    color: #1989fa;">
                            TOP
                        </div>
                    </el-backtop>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
// 引入过滤器
import common from '@/common/mixins/common.js'

import { mapState } from 'vuex';


export default {
    name: "AppLayout",

    // 注册
    mixins: [common],
    // 通过依赖注入让子组件获取loading状态（在image/index中使用）
    provide(){
        return {
            layout:this
        }
    },
    data() {
        return {
            // navBarIndex: "1",
            // navBar: {
            //     active: '0',
            // },
            bran: [],
            loading:false,
        };
    },
    created() {
        // // c初始化菜单
        // this.navBar = this.$conf.navBar;

        // 获取面包屑导航
        this.getRouterBran();

        // 初始化选中的菜单
        this._initNavBar();
    },
    // 过滤器应当封装,在common/mixin/common.js文件夹
    // filters:{
    //     numToString(value){
    //         return value.toString();
    //     }
    // },

    // 监听路由变化
    watch: {
        '$route': function () {
            this.getRouterBran();
        }
    },
    computed: {
        // slideMenuActive(){
        //     // 没有的话返回0
        //     return this.navBar.list[this.navBar.active].subActive || '0';
        // },

        // 设置按钮的激活
        sildeMenusActive: {
            get() {
                if (!this.navBar?.list?.[this.navBar.active]) {
                    return '0';
                }
                return this.navBar.list[this.navBar.active].subActive || '0';
            },
            set(val) {
                if (this.navBar?.list?.[this.navBar.active]) {
                    this.$set(this.navBar.list[this.navBar.active], 'subActive', val);
                }
            }
        },

        // 返回子目录
        slideMenus() {
            if (!this.navBar?.list?.[this.navBar.active]) {
                return [];
            }
            return this.navBar.list[this.navBar.active].submenu || [];
        },

        ...mapState({
            // 获取vuex中的数据
            // 指的是use模块中的user数据，名称要与src\store\index.js中的命名空间一致
            user: state => state.user.user,

            // 导入menu.js中从后端获取的权限菜单
            navBar: state => state.menu.navBar,
        }),
    },
    methods: {
        // 显示loading
        showLoading(){
            this.loading = true
        }       ,
         // 隐藏loading
         hideLoading(){
            this.loading = false
         },
        _initNavBar() {
            if (this.navBar?.list?.length > 0) {
                this.navBar.active = '0';
            }
        },
        handleSelect(key) {
            // console.log('顶部菜单点击：', key);
            
            // 处理特殊菜单项
            if (key === '100-1') {
                return console.log("修改个人资料");
            }
            if (key === "100-2") {
                return this.logout();
            }

            // 处理普通菜单项
            if (this.navBar?.list) {
                this.navBar.active = key;
                this.sildeMenusActive = '0';
                
                // 获取当前选中的菜单项
                const currentMenu = this.navBar.list[key];
                // console.log('当前选中的菜单：', currentMenu);
                
                if (currentMenu?.submenu?.length > 0) {
                    const firstSubmenu = currentMenu.submenu[0];
                    // console.log('第一个子菜单：', firstSubmenu);
                    
                    if (firstSubmenu.pathname) {
                        // 构建路由对象
                        const routeConfig = {
                            path: firstSubmenu.pathname === 'BackendIndex' ? '/index' : '/' + firstSubmenu.pathname,
                            name: firstSubmenu.pathname === 'BackendIndex' ? 'BackendIndex' : firstSubmenu.pathname.replace(/\//g, '-')
                        };
                        // console.log('准备跳转到：', routeConfig);
                        this.$router.push(routeConfig).catch(err => {
                            if (err.name !== 'NavigationDuplicated') {
                                console.error('路由跳转错误：', err);
                            }
                        });
                    } else {
                        console.warn('子菜单缺少pathname：', firstSubmenu);
                    }
                }
            }
        },
        sildeSelect(key) {
            // console.log('侧边菜单点击：', key);
            
            if (this.navBar?.list?.[this.navBar.active]) {
                this.$set(this.navBar.list[this.navBar.active], 'subActive', String(key));
                this.sildeMenusActive = String(key);

                const currentSubmenu = this.slideMenus?.[key];
                // console.log('当前选中的子菜单：', currentSubmenu);
                
                if (currentSubmenu?.pathname) {
                    // 构建路由对象
                    const routeConfig = {
                        path: '/' + currentSubmenu.pathname,
                        name: currentSubmenu.pathname.replace(/\//g, '-')
                    };
                    // console.log('准备跳转到：', routeConfig);
                    
                    if (this.$route.path !== routeConfig.path) {
                        this.$router.push(routeConfig).catch(err => {
                            if (err.name !== 'NavigationDuplicated') {
                                console.error('路由跳转错误：', err);
                            }
                        });
                    }
                } else {
                    console.warn('子菜单缺少pathname：', currentSubmenu);
                }
            }
        },

        // 获取面包屑导航
        getRouterBran() {
            let arr = [];
            let b = this.$route.matched.filter(v => v.name && v.name !== 'AppLayout'); // 只过滤掉 AppLayout

            // 处理匹配到的路由
            b.forEach((v) => {
                if (v.meta && v.meta.title) {  // 只添加有标题的路由
                    arr.push({
                        name: v.name,
                        path: v.path,
                        title: v.meta.title,
                    });
                }
            });

            // 如果当前不是首页，则添加首页链接
            if (this.$route.path !== '/index') {
                arr.unshift({
                    name: 'BackendIndex',
                    path: '/index',
                    title: '后台首页'
                });
            }

            this.bran = arr;
        },
        logout() {
            this.axios.post('/admin/logout', {}, {
                // headers: {
                //     token: this.user.token
                // }
                // 请求拦截器获取了token
                // 这里不需要传递token
                token:true,
                loading: true,
            }).then(() => {
                this.$message('退出成功');
                this.$store.commit('logout');
                // 返回到登录页
                this.$router.push({ name: 'login' });
            }).catch(() => {
                // 清除状态和存储
                this.$store.commit('logout');
                // 返回到登录页
                this.$router.push({ name: 'login' });
            })
        }
    }
};
</script>

<style>
html, body, #app, .login {
  height: 100%;
  min-height: 100%;
}

el-container{
    height:100%
}

/*滚动条整体样式*/
::-webkit-scrollbar {
    /*高宽分别对应横竖滚动条的尺寸*/
    width: 10px;
    height: 1px;
}

/*滚动条里面小方块*/
::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #535353;
}

/*滚动条里面轨道*/
::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: #EDEDED;
}
</style>